'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 帮助联盟成员
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var moment = require('moment');
var _ = require('lodash');
var constantUtil = require('../../../../util/constantUtil');
var Code = require('../../../../consts/code');
var unionGroupModel = require('../../../../models/unionGroupModel');
var unionGroupConf = require('../../../../config/unionGroupConf');
var unionHelpConf = require('../../../../config/unionHelpConf.js');
var PlayerManager = require('../../../../libs/playerManager');
var buildType = require('../../../../consts/buildType.js');
var taskService = require('../../../../services/taskService.js');
var unionHelpModel = require('../../../../models/unionHelpModel.js');
var haveHelpModel = require('../../../../models/haveHelpModel.js');
var haveHelpMgr = require('../../../../mgr/haveHelpMgr.js');
var unionGroupMgr = require('../../../../mgr/unionGroupMgr.js');

var is_new_version = false;

/**
 * 帮助联盟成员
 */
module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var union_group_model;
    var all_help_list = [];
    var all_have_list = [];
    var union_id = 0;
    var real_have_list = [];
    var real_help_list = [];
    // jshint maxdepth: 10
    // jshint maxstatements:150
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['role', 'build', 'tech', 'unionTask', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'], cb);
            },
            function (cb) {
                var role_model = player_manager.role;
                union_id = role_model.union_id;
                if (!union_id) {
                    return next(null, {
                        code: Code.UNION_IS_NOT_JOIN
                    });
                }
                unionGroupModel.getById(union_id, function (err, model) {
                    if (!model) {
                        return next(null, {
                            code: Code.UNION_IS_NOT_JOIN
                        });
                    }

                    union_group_model = model;
                    cb();
                });
            },
            function (cb) {
                unionHelpModel.findUnionHelpList(union_id, function (err, help_list) {
                    all_help_list = help_list;
                    cb();
                });
            },
            function (cb) {
                haveHelpModel.findUnionHelpList(role_id, function (err, list) {
                    all_have_list = list;
                    cb();
                });
            },
            function (cb) {
                _unionAllHelp(player_manager, union_group_model, all_help_list, all_have_list, function (err, modify_all_list) {
                    real_help_list = modify_all_list;
                    cb();
                });
            },
            function (cb) {
                // 帮助加声望
                var union_task_model = player_manager.unionTask;
                var union_help_reputation_reward = constantUtil.value('union_help_reputation_reward');
                union_task_model.helpAddReputation(union_help_reputation_reward * real_help_list.length);

                // 发送帮助列表和已帮助列表，删除相应次数已满已帮助列表
                _sendHelpList(role_id, union_id, real_help_list, cb);
            },
            function (cb) {
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            if (!!union_group_model) {
                union_group_model.save();
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

// 联盟帮助全部
var _unionAllHelp = function (player_manager, union_group_model, all_help_list, all_have_list, callback) {
    var real_help_list = [];
    var valid_help_list = [];
    var union_id = union_group_model.union_id;
    var role_id = player_manager.getRoleId();
    var map_have_help = {};

    _.forEach(all_have_list, function (item) {
        map_have_help[item.only_id] = item;
    });

    _.forEach(all_help_list, function (item) {
        var key = '' + item._id;
        if (!map_have_help[key] && item.help_max_num > 0 && item.role_id !== role_id) {
            valid_help_list.push(item);
        }
    });

    async.eachSeries(valid_help_list, function (union_help_item, cb) {
        _onlyHelpMsg(player_manager, union_group_model, union_help_item, union_id, role_id, function (err, back_help_item) {
            if (!!err) {
                console.error(err);
                return cb();
            }
            if (!!back_help_item) {
                real_help_list.push(back_help_item);
            }
            cb();
        });
    }, function (err) {
        if (!!err) {
            console.error(err);
        }
        callback(null, real_help_list);
    });
};

// 帮助单个人处理
var _onlyHelpMsg = function (player_manager, union_group_model, union_help_item, union_id, role_id, callback) {
    var help_role_id = union_help_item.role_id;
    var array_help = false;
    var union_task_model;
    var have_info = [];
    var find_info_item = null;
    var now_item = null;
    var back_list = [];
    var item_modify = null;
    var real_do_help = false;
    // jshint maxstatements:100
    var help_player_manager = new PlayerManager(help_role_id);
    async.waterfall(
        [
            function (cb) {
                help_player_manager.getModel(['role', 'build', 'tech'], cb);
            },
            function (cb) {
                // jshint maxdepth: 10
                var help_build_model = help_player_manager.build;
                var help_tech_model = help_player_manager.tech;
                union_task_model = player_manager.unionTask;

                // 建筑帮助
                if (union_help_item.help_type == 1) {
                    // 建筑是否在队列中
                    var build_id = union_help_item.share_id;
                    var build_item = help_build_model.getBuildSchedule(build_id);

                    if (!!build_item && build_item.build_id == build_id) {
                        real_do_help = true;
                        // 加速建筑
                        help_build_model.quick_schedule(build_id);
                    }
                }

                // 科技帮助
                if (union_help_item.help_type == 2) {
                    if (!!help_tech_model.up_tech_id && help_tech_model.up_tech_id == union_help_item.share_id) {
                        // 加速
                        var total_time = help_tech_model.up_tech_end_tm - help_tech_model.up_tech_start_tm;
                        if (total_time > 0) {
                            real_do_help = true;
                            var value = constantUtil.value('union_help_time_per');
                            var set_tech_time = parseInt(help_tech_model.up_tech_end_tm - total_time * (value / 100));
                            help_tech_model.setUpgradeTime(set_tech_time);
                        }
                    }
                }

                if (real_do_help) {
                    var max_num = union_help_item.help_max_num - 1;
                    item_modify = {
                        job: union_help_item.job,
                        share_id: union_help_item.share_id,
                        end_time: union_help_item.end_time,
                        help_type: union_help_item.help_type,
                        lv: union_help_item.lv,
                        help_max_num: max_num,
                        help_max_times: union_help_item.help_max_times,
                        name: union_help_item.name,
                        role_id: union_help_item.role_id,
                        union_id: union_help_item.union_id,
                        only_id: union_help_item._id.toString()
                    };

                    // 记录已帮助
                    have_info = [{
                        role_id: role_id,
                        union_id: union_help_item.union_id,
                        require_role_id: union_help_item.role_id,
                        share_id: union_help_item.share_id,
                        help_type: union_help_item.help_type,
                        only_id: union_help_item._id.toString()
                    }];

                    find_info_item = {
                        role_id: union_help_item.role_id,
                        union_id: union_help_item.union_id,
                        share_id: union_help_item.share_id,
                        help_type: union_help_item.help_type,
                    };
                    haveHelpModel.createHaveHelp(have_info, function (err) {
                        // 增加声望
                        var now_reputation = union_task_model.max_reputation;
                        var max_reputation = constantUtil.value('union_help_reputation_limit');
                        if (now_reputation < max_reputation) {
                            union_task_model.addReputation(constantUtil.value('union_help_reputation_reward'));
                        }

                        // 联盟帮助---全部帮助次数统计
                        taskService.addUnionHelpNum(player_manager);

                        // 刷新数据---帮助过后help_max_num - 1
                        var only_id_all_help = '' + union_help_item._id;
                        unionHelpModel.refreshHelpData(union_help_item, only_id_all_help, function (err) {
                            cb();
                        });
                    });
                } else {
                    cb();
                }
            },
            function (cb) {
                if (real_do_help) {
                    player_manager.save(cb);
                } else {
                    cb();
                }
            },

            function (cb) {
                if (real_do_help) {
                    help_player_manager.save(cb);
                } else {
                    cb();
                }
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
            }
            callback(null, item_modify);
        }
    );
};

/**
 * 推送帮助列表和已帮助列表
 */
var _sendHelpList = function (role_id, union_id, real_help_list, callback) {
    var help_modify_list = [];
    var help_remove_list = [];
    var have_modify_list = [];
    var have_remove_list = [];
    var remove_only_id_list = [];

    _.each(real_help_list, function (item) {
        if (item.help_max_num >= 1) {
            help_modify_list.push(item);

            have_modify_list.push({
                require_role_id: item.role_id,
                help_type: item.help_type,
                share_id: item.share_id
            });
        } else {
            help_remove_list.push(item);

            have_remove_list.push({
                require_role_id: item.role_id,
                help_type: item.help_type,
                share_id: item.share_id
            });

            remove_only_id_list.push(item.only_id);
        }
    });

    if (is_new_version) {
        // 新版所有帮助申请都采用修改同步
        _.each(help_remove_list, function (item) {
            help_modify_list.push(item);
        });
    }

    var list = {
        help_modify_list: help_modify_list,
        help_remove_list: help_remove_list,
        have_modify_list: have_modify_list,
        have_remove_list: have_remove_list,
        remove_only_id_list: remove_only_id_list
    };
    _doSendHelpList(role_id, union_id, list, callback);
};

/**
 * 执行实际推送
 */
var _doSendHelpList = function (role_id, union_id, list, callback) {
    var help_modify_list = list.help_modify_list;
    var help_remove_list = list.help_remove_list;
    var have_modify_list = list.have_modify_list;
    var have_remove_list = list.have_remove_list;
    var remove_only_id_list = list.remove_only_id_list;

    async.waterfall(
        [
            function (cb) {
                // 推送当前玩家--添加已帮助
                if (have_modify_list.length > 0) {
                    haveHelpMgr.sendHaveHelpChanged(
                        role_id, {
                            is_modify: 1,
                            have_list: have_modify_list
                        },
                        function (err, fails) {
                            if (err) {
                                console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                                return;
                            }
                            cb();
                        }
                    );
                } else {
                    cb();
                }

            },
            function (cb) {
                // 推送联盟--删除已帮助(次数已满)
                if (have_remove_list.length > 0) {
                    haveHelpMgr.sendHaveHelpChangedMulti(
                        union_id, {
                            is_modify: 2,
                            have_list: have_remove_list
                        },
                        function (err, fails) {
                            if (err) {
                                console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                                return;
                            }
                            cb();
                        }
                    );
                } else {
                    cb();
                }

            },
            function (cb) {
                // 推送联盟--同步帮助次数
                if (help_modify_list.length > 0) {
                    var msg = {
                        is_modify: 3,
                        help_list: help_modify_list
                    };
                    unionGroupMgr.sendUnioHelpChangedMulti(
                        union_id,
                        msg,
                        function (err, fails) {
                            if (err) {
                                console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                                return;
                            }
                            cb();
                        }
                    );
                } else {
                    cb();
                }
            },
            function (cb) {
                // 推送联盟(旧版)--删除次数已满帮助
                if (!is_new_version && help_remove_list.length > 0) {
                    var msg1 = {
                        is_modify: 2,
                        help_list: help_remove_list
                    };
                    unionGroupMgr.sendUnioHelpChangedMulti(
                        union_id,
                        msg1,
                        function (err, fails) {
                            if (err) {
                                console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                                return;
                            }
                            cb();
                        }
                    );
                } else {
                    cb();
                }
            },
            function (cb) {
                // 删除已帮助列表(次数已满)
                if (remove_only_id_list.length > 0) {
                    haveHelpModel.removeMsgList(remove_only_id_list, function (err) {
                        cb();
                    });
                } else {
                    cb();
                }
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
            }
            callback(null);
        }
    );
};
